package org.example.Interceptor;

import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.example.Utils.JwtUtil;
import org.example.Utils.LocalUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;



@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("放行前");
        String token = request.getHeader("token");
        String url = request.getRequestURI();

        //判断是否未登录操作,如果是则放行
        if(url.contains("/login")){
            //放行
            log.info("登录操作");
            return true;
        }
        //判断令牌是否为空
        if(token == null || token.isEmpty()){
            log.info("令牌为空或者不存在");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);//返回401状态码
            return false;
        }

        //校验令牌的正确性
        try {
            Claims claims = JwtUtil.parseToken(token);
            Integer id = (Integer) claims.get("id");
            LocalUtils.setCurrentId(id);

        } catch (Exception e) {
            log.info("令牌非法");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);//返回401状态码
            return false;
        }
        //解析令牌正确直接放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        LocalUtils.remove();
        log.info("放行后");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("图片渲染结束后");
    }
}
